/*
 * Developer : Jack Matthews
 * Email: developer@droidprofessor.com
 * 
 * Copyright (C) 2010 http://droidprofessor.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.droidprofessor.android.library.phonelicenses;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.droidprofessor.android.library.phonelicenses.R;
import com.droidprofessor.android.licensegenerator.client.AndroidClientLicenseImpl;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ActivityRegister extends Activity implements HttpResponseListener, OnClickListener {
	private static final String TAG = "CreateAccount";
	
	//controls
	private EditText nameEditText, usernameEditText, emailEditText, passwordEditText;
	private Button submitButton, cancelButton;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_LEFT_ICON);
		setContentView(R.layout.com_phonelicenses_register);
        getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, 
                R.drawable.com_phonelicenses_license_notification);
		getControls();
		
		//update from preferences
		if(savedInstanceState == null) {
			nameEditText.setText(PreferencesHelper.getName(this));
			usernameEditText.setText(PreferencesHelper.getUsername(this));
			passwordEditText.setText(PreferencesHelper.getPassword(this));
			emailEditText.setText(PreferencesHelper.getEmail(this));
		}
	}

	
	
	private void getControls() {
		nameEditText = (EditText)findViewById(R.id.edit_name);
		usernameEditText = (EditText)findViewById(R.id.edit_username);
		emailEditText = (EditText)findViewById(R.id.edit_email);
		passwordEditText = (EditText)findViewById(R.id.edit_password);
		
		cancelButton =  (Button)findViewById(R.id.button_cancel);
		cancelButton.setOnClickListener(this);
		submitButton = (Button)findViewById(R.id.button_submit);
		submitButton.setOnClickListener(this);
	}
	

	
	@Override
	protected void onResume() {
		super.onResume();
	}
	

	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		try {
			outState.putString("username", usernameEditText.getText().toString());
			outState.putString("password", passwordEditText.getText().toString());
			outState.putString("name", nameEditText.getText().toString());
			outState.putString("email", emailEditText.getText().toString());	
		} catch (Exception e) {
			//Maybe the TextView were not initialized yet
		}
		
		super.onSaveInstanceState(outState);
	}








	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		
		String username = savedInstanceState.getString("username");
		String password = savedInstanceState.getString("password");
		String name = savedInstanceState.getString("name");
		String email = savedInstanceState.getString("email");
		
		if(username != null)
			usernameEditText.setText(username);
		if(password != null)
			passwordEditText.setText(password);
		if(name != null)
			nameEditText.setText(name);
		if(email != null)
			emailEditText.setText(email);
		
		
	}

	/**
	 * Validate the user form
	 * 
	 * @return true of success
	 */
	private boolean validateForm() {
		if( !ValidationHelper.validateName(this, nameEditText.getText().toString())) return false;
		if( !ValidationHelper.validateUsername(this, usernameEditText.getText().toString())) return false;
		if( !ValidationHelper.validatePassword(this, passwordEditText.getText().toString())) return false;
		if( !ValidationHelper.validateEmailAddress(this, emailEditText.getText().toString())) return false;				

	    return true;
	}
	
	
	/**
	 * Send a new Account request the the server
	 * 
	 * @return String HTTP response
	 */
	private void createNewAccount() {
			if( !Utils.gotInternetConnection(this) ) {
				Toast.makeText(this, R.string.com_phonelicenses_no_internet, Toast.LENGTH_SHORT);
				return;
			}
		
			setProgressBarIndeterminateVisibility(true);
		
			//Registration data
			List<NameValuePair> post = new ArrayList<NameValuePair>();
			post.add(new BasicNameValuePair("name", nameEditText.getText().toString() ));    
			post.add(new BasicNameValuePair("username", usernameEditText.getText().toString() )); 
			post.add(new BasicNameValuePair("email", emailEditText.getText().toString() )); 
			post.add(new BasicNameValuePair("password", passwordEditText.getText().toString() )); 
			post.add(new BasicNameValuePair("password2", passwordEditText.getText().toString() )); 
			post.add(new BasicNameValuePair("auth_key", AndroidClientLicenseImpl.getInstance().getAuthKey() ));
			
			//Joomla requirements
			List<NameValuePair> get = new ArrayList<NameValuePair>();
			get.add(new BasicNameValuePair("option", "com_phonelicenses" ));    
			get.add(new BasicNameValuePair("view", "user" ));    
			get.add(new BasicNameValuePair("controller", "user" ));    
			get.add(new BasicNameValuePair("task", "register" ));    
			get.add(new BasicNameValuePair("format", "xml" ));    
			
			HttpUrlRequest.sendRequest(
					AndroidClientLicenseImpl.getInstance().getScheme(),
					AndroidClientLicenseImpl.getInstance().getHost(),
					AndroidClientLicenseImpl.getInstance().getPort(), 
					AndroidClientLicenseImpl.getInstance().getPath(),
					get, 
					post,
					PhoneLicensesCodes.REQUEST_CODE_NEW_ACCOUNT, 
					this);
	}
	
	
	
	
	
	@Override
	public void onResponseReceived(HttpResponse response, int requestCode) {
		//Common code required by all HTTP responses
		if(response==null) {
			Toast.makeText(this, R.string.com_phonelicenses_communication_error , Toast.LENGTH_LONG).show();
			return;
		}
		
		HttpEntity entity = response.getEntity();
		BufferedInputStream bis;
		
		try {
			if(entity != null) {
				InputStream in = entity.getContent();
				bis = new BufferedInputStream(in);
				Utils.logInpuStream(bis);
			}
			else {
				Toast.makeText(this, R.string.com_phonelicenses_no_internet, Toast.LENGTH_LONG);
				return;
			}
		} catch (IllegalStateException e) {
			Log.e(TAG, "IllegalStateException", e);
			return;
		} catch (IOException e) {
			Log.e(TAG, "IOException", e);
			return;
		} finally {
			//hide the progress bar
			dismissDialog(PhoneLicensesCodes.DIALOG_PROGRESS);
			setProgressBarIndeterminateVisibility(false);
		}
		
		
		
		
		switch (requestCode) {
		case PhoneLicensesCodes.REQUEST_CODE_NEW_ACCOUNT:			
			XmlResponse<Void> xmlResponse = XmlParser.parseXmlResponse(bis);

			if(xmlResponse.isError()) {
				//notify the user
				dialogMessage = xmlResponse.getMessage();
				showDialog(PhoneLicensesCodes.DIALOG_MESSAGE);
				Log.e(TAG, xmlResponse.toString() );	
			} else { //ALL WAS OK
				Log.d(TAG, xmlResponse.getMessage());
				PreferencesHelper.setAccountVerified(this); //mark as verified
				//setResult(PhoneLicensesCodes.RESULT_CODE_REGISTERED);
				finish(); //return control
			}
			
			break;
		default:
			break;
		}
	}

	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.button_submit:
				if(validateForm()) {
					PreferencesHelper.updatePreferences(
							this, 
							nameEditText.getText().toString(),
							usernameEditText.getText().toString(), 
							passwordEditText.getText().toString(),
							emailEditText.getText().toString());
					showDialog(PhoneLicensesCodes.DIALOG_PROGRESS);
					createNewAccount();
				}
				break;
			case R.id.button_cancel:
				finish();
				break;
		}
	}
	
	
	
//	private ProgressDialog progressDialog;
//	private void showProgress() {
//		progressDialog = ProgressDialog.show(
//				this,
//				String.format(
//						getResources().getString(R.string.com_phonelicenses_contacting_x),
//						ApplicationDataCache.getInstance().getMerchantName()
//						), 				
//				getResources().getString(R.string.com_phonelicenses_please_wait), 
//				false, 
//				false
//				);
//	}
	
	
	
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		
		switch (id) {
		case PhoneLicensesCodes.DIALOG_MESSAGE:
			dialog = new AlertDialog.Builder(this)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setMessage(dialogMessage)
			.setPositiveButton(R.string.com_phonelicenses_ok, null)
			.create();
			break;
		case PhoneLicensesCodes.DIALOG_PROGRESS:
			dialog = new ProgressDialog(this);
			dialog.setTitle(getString(R.string.com_phonelicenses_please_wait));
			((ProgressDialog)dialog).setMessage("");
			((ProgressDialog)dialog).setProgressStyle(ProgressDialog.STYLE_SPINNER);
			((ProgressDialog)dialog).setCancelable(false);
			((ProgressDialog)dialog).setIndeterminate(false);		
			((ProgressDialog)dialog).setButton(getString(R.string.com_phonelicenses_cancel), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			break;
		default:
			dialog = null;
			break;
		}
		
		return dialog;
	}
	
	




	private String dialogMessage = "";
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
		
		switch (id) {
		case PhoneLicensesCodes.DIALOG_MESSAGE:
			((AlertDialog)dialog).setMessage(dialogMessage);
			break;
		case PhoneLicensesCodes.DIALOG_PROGRESS:
			((ProgressDialog)dialog).setMessage(
					String.format(
					getResources().getString(R.string.com_phonelicenses_contacting_x),
					ApplicationDataCache.getInstance().getMerchantName()
					)
				); //update the dialog each time
			break;
		default:
			break;
		}
	}

	
}
